package com.springboot.file.util.easyexcel.converter;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.springboot.file.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import java.util.Date;

/**
 * Date转换器
 */
@Slf4j
public class CustomDateConverter implements Converter<Date> {

    @Override
    public Class<Date> supportJavaTypeKey() {
        return Date.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Date convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (ObjectUtil.isEmpty(cellData)) {
            return null;
        }

        try {
            log.debug("日期转换 - 类型: {}, 值: {}", cellData.getType(), cellData.getData());

            if (CellDataTypeEnum.NUMBER.equals(cellData.getType())) {
                if (ObjectUtil.isEmpty(cellData.getNumberValue())) {
                    return null;
                }
                // Excel的日期起始点是1900-01-01，且有一个1900-02-29的bug需要处理
                // 如果大于60（1900-02-29）需要减1处理Excel的日期Bug
                long daysSince1900 = cellData.getNumberValue().longValue() > 60 ? 
                    cellData.getNumberValue().longValue() - 2 : 
                    cellData.getNumberValue().longValue() - 1;
                // 1900-01-01对应的时间戳
                long jan1st1900 = -2209017600000L; // 1900-01-01 00:00:00 GMT
                // 一天的毫秒数
                long oneDayMillis = 24 * 60 * 60 * 1000L; // 一天的毫秒数 = 24小时 * 60分钟/小时 * 60秒/分钟 * 1000毫秒/秒
                // 计算结果时间戳
                long resultTimestamp = jan1st1900 + (daysSince1900 * oneDayMillis);
                return new Date(resultTimestamp);
            } else {
                if (cellData.getStringValue() == null || cellData.getStringValue().trim().isEmpty()) {
                    return null;
                }
                return DateUtil.convertObjToUtilDate(cellData.getStringValue());
            }
        } catch (Exception e) {
            log.error("日期转换失败 - 类型: {}, 值: {}, 错误: {}",
                    cellData.getType(), cellData.getData(), e.getMessage());
            return null;
        }
    }

    @Override
    public WriteCellData<?> convertToExcelData(Date value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (ObjectUtil.isEmpty(value)) {
            return new WriteCellData<>("");
        }
        return new WriteCellData<>(DateUtil.convertObjToString(value, DateUtil.DATE_FORMATTER_3));
    }
} 